 
package com.zdkj.subway.rca.service.impl;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.util.DateUtils;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.metadata.fill.FillConfig;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zdkj.common.security.service.PigxUser;
import com.zdkj.common.security.util.SecurityUtils;
import com.zdkj.subway.rca.entity.ViewCkDataauditAirReportCheck;
import com.zdkj.subway.rca.mapper.ViewCkDataauditAirReportCheckMapper;
import com.zdkj.subway.rca.service.ViewCkDataauditAirReportCheckService;
import com.zdkj.subway.rca.util.LocalDateConverter;
import com.zdkj.subway.rca.util.LocalDateTimeConverter;
import com.zdkj.subway.rca.util.MyDateUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 所有运营商收入报表与对账数据复核
 *
 * @author stw
 * @date 2020-11-15 12:50:53
 */
@Service
public class ViewCkDataauditAirReportCheckServiceImpl extends ServiceImpl<ViewCkDataauditAirReportCheckMapper, ViewCkDataauditAirReportCheck> implements ViewCkDataauditAirReportCheckService {
    private static final Logger log = LoggerFactory.getLogger(ViewCkDataauditAirReportCheckServiceImpl.class);

    /**
     * 产生数据
     * @return
     */
    @Override
    public Boolean generate(String startDate,String endDate) throws Exception {

        List<String> listDate = MyDateUtil.getDatesBetweenTwoDate(startDate,endDate);

        //通用查询方法
        List<Map<String,Object>> dataListDailyReport = this.baseMapper.getDataListDailyReport(startDate,endDate);

        //根据日期范围获取数据list         
//        List<Map<String,Object>> dataListA = this.baseMapper.getDataListA(startDate,endDate);
//        List<Map<String,Object>> dataListB = this.baseMapper.getDataListB(startDate,endDate);
        List<Map<String,Object>> dataListC = this.baseMapper.getDataListC(startDate,endDate);
        List<Map<String,Object>> dataListD = this.baseMapper.getDataListD(startDate,endDate);
        
		
		//List<Map<String,Object>> dataListE = this.baseMapper.getDataListE(startDate,endDate);
        //List<Map<String,Object>> dataListF = this.baseMapper.getDataListF(startDate,endDate);
		List<Map<String,Object>> dataListF1 = this.baseMapper.getDataListF1(startDate,endDate);
		List<Map<String,Object>> dataListF2 = this.baseMapper.getDataListF2(startDate,endDate);
		List<Map<String,Object>> dataListF3 = this.baseMapper.getDataListF3(startDate,endDate);
		List<Map<String,Object>> dataListF4 = this.baseMapper.getDataListF4(startDate,endDate);
        
//		List<Map<String,Object>> dataListG = this.baseMapper.getDataListG(startDate,endDate); //长安通系统清分
//		List<Map<String,Object>> dataListG0 = this.baseMapper.getDataListG0(startDate,endDate); //交通卡系统清分
//		List<Map<String,Object>> dataListG1 = this.baseMapper.getDataListG1(startDate,endDate);  //充值---长安通BOM现金
//		List<Map<String,Object>> dataListG2 = this.baseMapper.getDataListG2(startDate,endDate);  //充值---长安通BOM支付宝
//		List<Map<String,Object>> dataListG3 = this.baseMapper.getDataListG3(startDate,endDate);  //充值---长安通BOM微信
//		List<Map<String,Object>> dataListG4 = this.baseMapper.getDataListG4(startDate,endDate);  //充值---长安通TVM现金
//		List<Map<String,Object>> dataListG5 = this.baseMapper.getDataListG5(startDate,endDate);  //充值---长安通TVM支付宝
//		List<Map<String,Object>> dataListG6 = this.baseMapper.getDataListG6(startDate,endDate);  //充值---长安通TVM微信
//		List<Map<String,Object>> dataListG7 = this.baseMapper.getDataListG7(startDate,endDate);  //充值---长安通TVM银行

        List<Map<String,Object>> dataListH = this.baseMapper.getDataListH(startDate,endDate);

        List<Map<String,Object>> dataListJ = this.baseMapper.getDataListJ(startDate,endDate);

        List<Map<String,Object>> dataListL = this.baseMapper.getDataListL(startDate,endDate);
        //List<Map<String,Object>> dataListM = this.baseMapper.getDataListM(startDate,endDate);
        List<Map<String,Object>> dataListN = this.baseMapper.getDataListN(startDate,endDate);
        List<Map<String,Object>> dataListO = this.baseMapper.getDataListO(startDate,endDate);
        List<Map<String,Object>> dataListP = this.baseMapper.getDataListP(startDate,endDate);
        //List<Map<String,Object>> dataListQ = this.baseMapper.getDataListQ(startDate,endDate);
        List<Map<String,Object>> dataListR = this.baseMapper.getDataListR(startDate,endDate);

        List<Map<String,Object>> dataListS = this.baseMapper.getDataListS(startDate,endDate);
        List<Map<String,Object>> dataListT = this.baseMapper.getDataListT(startDate,endDate);

		List<Map<String,Object>> dataListWechatCompare = this.baseMapper.getDataListWechatapp(startDate,endDate);

        List<ViewCkDataauditAirReportCheck> updaeList = new ArrayList<>();
        List<ViewCkDataauditAirReportCheck> insertList = new ArrayList<>();

        PigxUser user = SecurityUtils.getUser();

        //循环时间段内每一天
        for(String tradeDate : listDate) {
            ViewCkDataauditAirReportCheck insertObj = new ViewCkDataauditAirReportCheck();
            insertObj.setStatisticsDate(LocalDate.parse(tradeDate, DateTimeFormatter.ofPattern("yyyy-MM-dd")));

            //数据库老的
            ViewCkDataauditAirReportCheck dbViewCkDataauditAirReportCheck = this.getOne(Wrappers.query(insertObj));
            if (dbViewCkDataauditAirReportCheck != null){
                insertObj.setId(dbViewCkDataauditAirReportCheck.getId());
            }
            //BOM小额  初始：BOM小额支付平台  ，对账 西安地铁支付宝、微信二维码BOM确认表 c和d需要需要减去手续费
            insertObj.setBomAlipay(getData(tradeDate,"BOM_ALIPAY",dataListDailyReport));
            insertObj.setBomWechat(getData(tradeDate,"BOM_WECHAT",dataListDailyReport));
            insertObj.setBomAlipayCompare(getData(tradeDate,"BOM_ALIPAY_COMPARE",dataListC));//西安地铁支付宝二维码BOM确认表
            insertObj.setBomWechatCompare(getData(tradeDate,"BOM_WECHAT_COMPARE",dataListD));
            insertObj.setDiffBomAlipay(insertObj.getBomAlipay().subtract(insertObj.getBomAlipayCompare()));
            insertObj.setDiffBomWechat(insertObj.getBomWechat().subtract(insertObj.getBomWechatCompare()));
            
			//二维码  初始非现金收入审核  二维码 sw_ck_distinct_payment_qr    
            insertObj.setQrAlipay(getData(tradeDate,"QR_ALIPAY",dataListDailyReport));
            insertObj.setQrWechat(getData(tradeDate,"QR_WECHAT",dataListDailyReport));
			insertObj.setQrWechatApp(getData(tradeDate,"QR_WECHAT_APP",dataListDailyReport));
            insertObj.setQrBank(getData(tradeDate,"QR_BANK",dataListDailyReport));
            //二维码对照  对西安地铁支付宝二维码消费过闸确认表
            insertObj.setQrAlipayCompare(getData(tradeDate,"QR_ALIPAY_COMPARE",dataListF1));
            insertObj.setQrWechatCompare(getData(tradeDate,"QR_WECHAT_COMPARE",dataListF2));
			insertObj.setQrWechatAppCompare(getData(tradeDate,"QR_WECHAT_APP_COMPARE",dataListWechatCompare));//微信小程序对账
            insertObj.setQrBankCompare(getData(tradeDate,"QR_BANK_COMPARE",dataListF3));
            insertObj.setQrBankCompare(insertObj.getQrBankCompare().add(getData(tradeDate,"QR_BANK_COMPARE",dataListF4)));
            insertObj.setDiffQrAlipay(insertObj.getQrAlipay().subtract(insertObj.getQrAlipayCompare()));
            insertObj.setDiffQrWechat(insertObj.getQrWechat().subtract(insertObj.getQrWechatCompare()));
			insertObj.setDiffQrWechatApp(insertObj.getQrWechatApp().subtract(insertObj.getQrWechatAppCompare()));
            insertObj.setDiffQrBank(insertObj.getQrBank().subtract(insertObj.getQrBankCompare()));

            //长安通系统清分   dataListG需要确认ACC接口里是
            insertObj.setCatcardSystem(getData(tradeDate,"CATCARD_SYSTEM",dataListDailyReport));
            insertObj.setCatcardSysttemCompare(getData(tradeDate,"CATCARD_SYSTTEM_COMPARE",dataListH));
            insertObj.setDiffCatcardSysttem(insertObj.getCatcardSystem().subtract(insertObj.getCatcardSysttemCompare()));

            //长安通充值  7个充值 sw_ck_statement_cat_replenish 长安通充资对账确认表
			insertObj.setRecharge(getData(tradeDate,"RECHARGE",dataListDailyReport));
            //insertObj.setRecharge(insertObj.getRecharge().add(getData(tradeDate,"RECHARGE",dataListDailyReport)));
			//insertObj.setRecharge(insertObj.getRecharge().add(getData(tradeDate,"RECHARGE",dataListDailyReport)));
			//insertObj.setRecharge(insertObj.getRecharge().add(getData(tradeDate,"RECHARGE",dataListDailyReport)));
			//insertObj.setRecharge(insertObj.getRecharge().add(getData(tradeDate,"RECHARGE",dataListDailyReport)));
			//insertObj.setRecharge(insertObj.getRecharge().add(getData(tradeDate,"RECHARGE",dataListDailyReport)));
			//insertObj.setRecharge(insertObj.getRecharge().add(getData(tradeDate,"RECHARGE",dataListDailyReport)));
            insertObj.setRechargeCompare(getData(tradeDate,"RECHARGE_COMPARE",dataListJ));
            insertObj.setDiffRecharge(insertObj.getRecharge().subtract(insertObj.getRechargeCompare()));

            //交通卡  交通卡充资对账确认表
            insertObj.setJtcardSystem(getData(tradeDate,"JTCARD_SYSTEM",dataListDailyReport));
            insertObj.setJtcardSysttemCompare(getData(tradeDate,"JTCARD_SYSTTEM_COMPARE",dataListL));
            insertObj.setDiffJtcardSysttem(insertObj.getJtcardSystem().subtract(insertObj.getJtcardSysttemCompare()));

            //ITVM 非现金收入审核TVM电子平台导入  
            insertObj.setItvmAlipay(getData(tradeDate,"ITVM_ALIPAY",dataListDailyReport));
            insertObj.setItvmWechat(getData(tradeDate,"ITVM_WECHAT",dataListDailyReport));
            insertObj.setItvmBank(getData(tradeDate,"ITVM_BANK",dataListDailyReport));
            //ITVM确认表需要用金额-手续费
            insertObj.setItvmAlipayCompare(getData(tradeDate,"ITVM_ALIPAY_COMPARE",dataListN));
            insertObj.setItvmWechatCompare(getData(tradeDate,"ITVM_WECHAT_COMPARE",dataListO));
            insertObj.setItvmBankCompare(getData(tradeDate,"ITVM_BANK_COMPARE",dataListP));
            insertObj.setDiffItvmAlipay(insertObj.getItvmAlipay().subtract(insertObj.getItvmAlipayCompare()));
            insertObj.setDiffItvmWechat(insertObj.getItvmWechat().subtract(insertObj.getItvmWechatCompare()));
            insertObj.setDiffItvmBank(insertObj.getItvmBank().subtract(insertObj.getItvmBankCompare()));

            //应急及互联互通 非现金收入审核TVM电子平台导入
            insertObj.setConnectivityAlipay(getData(tradeDate,"CONNECTIVITY_ALIPAY",dataListDailyReport));
            insertObj.setConnectivityWechat(getData(tradeDate,"CONNECTIVITY_WECHAT",dataListDailyReport));
            //应急及互联互通 确认表需要用金额-手续费
            insertObj.setConnectivityAlipayCompare(getData(tradeDate,"CONNECTIVITY_ALIPAY_COMPARE",dataListS));
            insertObj.setConnectivityWechatCompare(getData(tradeDate,"CONNECTIVITY_WECHAT_COMPARE",dataListT));
            insertObj.setDiffConnectivityAlipay(insertObj.getConnectivityAlipay().subtract(insertObj.getConnectivityAlipayCompare()));
            insertObj.setDiffConnectivityWechat(insertObj.getConnectivityWechat().subtract(insertObj.getConnectivityWechatCompare()));

            //人脸  非现金收入审核  对照  对账确认表的人脸数据
            insertObj.setFaceBank(getData(tradeDate,"FACE_BANK",dataListDailyReport));
            insertObj.setFaceBankCompare(getData(tradeDate,"FACE_BANK_COMPARE",dataListR));
            insertObj.setDiffFaceBank(insertObj.getFaceBank().subtract(insertObj.getFaceBankCompare()));

            insertObj.setDeptId(user.getDeptId());
            insertObj.setCreatorId(user.getId());
            insertObj.setCreatorName(user.getNikeName());
            if(insertObj.getId() != null){
                updaeList.add(insertObj);
            } else {
                insertList.add(insertObj);
            }

        }
        boolean flag = false;
        boolean flag2 = false;
        if(!updaeList.isEmpty()){
            //flag = this.updateBatchById(updaeList);
            //MP的字段默认更新策略
            for (ViewCkDataauditAirReportCheck reportCheck : updaeList) {
                flag = this.update(reportCheck, Wrappers.<ViewCkDataauditAirReportCheck>lambdaUpdate()
                        .set(ViewCkDataauditAirReportCheck::getConformStatus, "0")
                        .set(ViewCkDataauditAirReportCheck::getConformTime, null).eq(ViewCkDataauditAirReportCheck::getId, reportCheck.getId()));
            }
        }
        if(!insertList.isEmpty()){
            flag2 = this.saveBatch(insertList);
        }
        return  flag || flag2;
    }
    private BigDecimal getData(String tradeDate, String key, List<Map<String,Object>> dataList){
        if(dataList == null || dataList.isEmpty()) {
            return new BigDecimal(0);
        }
        for(Map<String,Object> map : dataList) {
            if(tradeDate.equals(DateUtils.format((Date)map.get("TRADE_DATE"),"yyyy-MM-dd"))) {
                return (BigDecimal) map.get(key);
            }
        }
        return new BigDecimal(0);
    }
    /**
     * 导出
     * @param
     * @return
     * @throws IOException
     */
    @Override
    public void exportExcel(String startDate, String endDate, HttpServletResponse response) {
        ViewCkDataauditAirReportCheck viewCkDataauditAirReportCheck = new ViewCkDataauditAirReportCheck();
        List<ViewCkDataauditAirReportCheck> records  = this.list(Wrappers.query(viewCkDataauditAirReportCheck).lambda().ge(StringUtils.isNotEmpty(startDate), ViewCkDataauditAirReportCheck::getStatisticsDate, startDate).le( StringUtils.isNotEmpty(endDate),ViewCkDataauditAirReportCheck::getStatisticsDate, endDate));
        InputStream excelTemplateIs = null;
        try {response.reset(); // 非常重要
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            final String fileName = URLEncoder.encode("所有运营商收入报表与对账数据复核", "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + System.currentTimeMillis() + ".xlsx");

            // 模板注意 用{} 来表示你要用的变量 如果本来就有"{","}" 特殊字符 用"\{","\}"代替
            // {} 代表普通变量 {.} 代表是list的变量

            excelTemplateIs = this.getClass().getResourceAsStream("/static/excel/template/export/ViewCkDataauditAirReportCheckExcelTemplate.xlsx");

            ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream()).registerConverter(new LocalDateTimeConverter()).registerConverter(new LocalDateConverter()).withTemplate(excelTemplateIs).build();
            WriteSheet writeSheet = EasyExcel.writerSheet("所有运营商收入报表与对账数据复核").build();
            // 这里注意 入参用了forceNewRow 代表在写入list的时候不管list下面有没有空行 都会创建一行，然后下面的数据往后移动。默认 是false，会直接使用下一行，如果没有则创建。
            // forceNewRow 如果设置了true,有个缺点 就是他会把所有的数据都放到内存了，所以慎用
            // 简单的说 如果你的模板有list,且list不是最后一行，下面还有数据需要填充 就必须设置 forceNewRow=true 但是这个就会把所有数据放到内存 会很耗内存
            // 如果数据量大 list不是最后一行 参照另一个
            FillConfig fillConfig = FillConfig.builder().forceNewRow(Boolean.FALSE).build();
            excelWriter.fill(records, fillConfig, writeSheet);

            excelWriter.finish();

        } catch (Exception e) {
            e.printStackTrace();
            log.error("导出所有运营商收入报表与对账数据复核错误");
        } finally {
            if(excelTemplateIs != null){
                try {
                    excelTemplateIs.close();
                } catch (IOException ioe) {
                    ioe.printStackTrace();
                }

            }
        }
    }
}
